import JSZip from 'jszip';

export default defineContentScript({
  matches: [
    'https://www.dianxiaomi.com/web/popTemu/edit*',
    'https://www.dianxiaomi.com/web/popTemu/add',
  ],
  runAt: 'document_start',
  world: 'MAIN',
  async main() {
    const originSend = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function (...args) {
      const data = args[0];
      if (data instanceof FormData) {
        const file = data.get('file') as File;
        if (file && file.type === 'application/zip') {
          // 把 file 进行 zip 解压缩
          const zip = new JSZip();
          zip
            .loadAsync(file)
            .then((zip) => {
              zip.forEach((relativePath, zipEntry) => {
                zipEntry.async('string').then((content) => {
                  console.log(`File: ${relativePath}`);
                  console.log(content);
                  console.log(JSON.parse(content));
                });
              });
            })
            .catch((error) => {
              console.error('Error loading zip file:', error);
            });
        }
      }
      return originSend.apply(this, args);
    };
  },
});
